package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.xuanzheng.company.entity.Task;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.TaskService;
import com.xuanzheng.company.service.impl.TaskServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.stream.Collectors;

@WebServlet("/api/task/create")
public class CreateTaskServlet extends HttpServlet {
    private final TaskService taskService = new TaskServiceImpl();
    // 使用GsonBuilder创建Gson实例，确保正确处理中文字符
    private final Gson gson = new GsonBuilder().disableHtmlEscaping().create();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求和响应的字符编码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        JsonObject result = new JsonObject();

        try {
            // 检查用户是否登录
            HttpSession session = req.getSession();
            User user = (User) session.getAttribute("user");
            if (user == null) {
                result.addProperty("success", false);
                result.addProperty("message", "请先登录");
                out.print(gson.toJson(result));
                return;
            }

            // 检查用户是否是公司负责人
            if (user.getRole() != 1) { // 假设role=1为公司负责人
                result.addProperty("success", false);
                result.addProperty("message", "只有公司负责人可以派遣任务");
                out.print(gson.toJson(result));
                return;
            }

            // 获取请求体
            String requestBody = req.getReader().lines().collect(Collectors.joining());
            Task task = gson.fromJson(requestBody, Task.class);

            // 设置公司ID和管理者ID
            task.setCompanyId(user.getCompanyId());
            task.setManagerId(user.getId());

            // 创建任务
            boolean success = taskService.createTask(task);

            if (success) {
                result.addProperty("success", true);
                result.addProperty("message", "任务派遣成功");
            } else {
                result.addProperty("success", false);
                result.addProperty("message", "任务派遣失败");
            }
        } catch (Exception e) {
            result.addProperty("success", false);
            result.addProperty("message", "系统错误: " + e.getMessage());
            e.printStackTrace();
        }

        out.print(gson.toJson(result));
    }
} 